<template>
  <a-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="客户料号">
              <a-input placeholder="请输入客户料号" v-model="queryParam.clientCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料料号">
              <a-input placeholder="请输入物料料号" v-model="queryParam.materielCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="规格">
              <a-input placeholder="请输入规格" v-model="queryParam.materielGauge"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="mainId">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('订单管理—采购订单子表')">导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!--      <a-button style="margin-left: 8px" type="primary" @click="print"> 打印 </a-button>-->

      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
        style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :scroll="{ x: 2500 }"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt=""
               style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="uploadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handlePrint(record)">打印</a>
          <a-divider type="vertical" />
           <a-dropdown>
            <a class="ant-dropdown-link">更多
              <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
              <a>删除</a>
            </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
               <a @click="updateNum(record.id)">更新未收货数量</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>

    <mesPurchaseItem-modal ref="modalForm" @ok="modalFormOk" :mainId="mainId"></mesPurchaseItem-modal>
    <a-modal v-model="visiblePrint" title="打印" @ok="handleOk">
      <a-form
        :form="form"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-form-item label="批次">
          <a-input v-decorator="['batchNum', rules.batchNum]" />
        </a-form-item>
        <a-form-item label="客户料号" name="clientCode">
          <a-input v-decorator="['clientCode']" />
        </a-form-item>
        <a-form-item label="批次数量" name="batch">
          <a-input v-decorator="['batch', rules.batch]" />
        </a-form-item>
        <a-form-item label="打印张数" name="printNum">
          <a-input v-decorator="['printNum', rules.printNum]" />
        </a-form-item>
        <a-form-item label="备注">
          <a-input v-model:value="handform.remark" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import MesPurchaseItemModal from './modules/MesPurchaseItemModal'
import { dateFormat } from '@/utils/util'
import pick from 'lodash.pick'
import { getAction, httpAction } from '@api/manage'

export default {
  name: 'MesPurchaseItemList',
  mixins: [JeecgListMixin],

  components: { MesPurchaseItemModal },
  props: {
    mainId: {
      type: String,
      default: '',
      required: false
    }
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList()
        } else {
          this.queryParam['purchaseId'] = val
          this.loadData(1)
        }
      }
    }
  },
  data() {
    let validatorBatch=(rule,value,callback)=>{
      // 正则判断手机号格式的格式，正则判断失败抛出错误，否则直接callback()
      if(Number(this.unPrintNum) < Number(value)){
        callback(new Error('当前未打印数量为'+this.unPrintNum+'，请输入正确的批次数量'));
      }else{
        callback();
      }
    }
    return {
      description: '订单管理—采购订单管理页面',
      disableMixinCreated: true,
      visiblePrint: false,
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        span: 4
      },
      wrapperCol: {
        span: 14
      },
      handform: {},
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        // {
        //   title:'行号',
        //   align:"center",
        //   dataIndex: 'rowNum'
        // },
        {
          title: '料号',
          align: 'center',
          dataIndex: 'materielCode'
        },
        {
          title: '客户料号',
          align: 'center',
          dataIndex: 'clientCode'
        },
        {
          title: '品名',
          align: 'center',
          dataIndex: 'materielName'
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'materielGauge'
        },
        {
          title: '封装',
          align: 'center',
          dataIndex: 'query5'
        },
        {
          title: '伏数',
          align: 'center',
          dataIndex: 'query6'
        },
        {
          title: '误差',
          align: 'center',
          dataIndex: 'rowNum'
        },
        {
          title: '采购数量',
          align: 'center',
          dataIndex: 'purchaseNum'
        },
        {
          title: '未收货数量',
          align: 'center',
          dataIndex: 'unreceiveNum'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'orderUnit'
        },
        {
          title: '最小包装数',
          align: 'center',
          dataIndex: 'query4'
        },
        {
          title: '净价',
          align: 'center',
          dataIndex: 'grossPrice'
        },
        {
          title: '货币',
          align: 'center',
          dataIndex: 'currency_dictText'
        },
        {
          title: '交货日期',
          align: 'center',
          dataIndex: 'deliveryDate'
        },
        // {
        //   title:'物料组',
        //   align:"center",
        //   dataIndex: 'materielTeam_dictText',
        // },
        {
          title: '工厂编号',
          align: 'center',
          dataIndex: 'factoryCode'
        },
        {
          title: '工厂名称',
          align: 'center',
          dataIndex: 'factoryName'
        },
        {
          title: '库存地点',
          align: 'center',
          dataIndex: 'storageSite'
        },
        {
          title: '物料标记',
          align: 'center',
          dataIndex: 'imgExgFlag'
        },
        // {
        //   title:'项号',
        //   align:"center",
        //   dataIndex: 'itemNo'
        // },
        // {
        //   title:'批次号',
        //   align:"center",
        //   dataIndex: 'sectionNo'
        // },
        // {
        //   title:'公司编码',
        //   align:"center",
        //   dataIndex: 'companyCode'
        // },
        // {
        //   title:'公司编码',
        //   align:"center",
        //   dataIndex: 'companyCode'
        // },
        {
          title: '板数',
          align: 'center',
          dataIndex: 'palletNum'
        },
        {
          title: '件数',
          align: 'center',
          dataIndex: 'pcs'
        },
        {
          title: '包装总类',
          align: 'center',
          dataIndex: 'wrap'
        },
        {
          title: '箱号',
          align: 'center',
          dataIndex: 'containerNo'
        },
        {
          title: '净重',
          align: 'center',
          dataIndex: 'netWeight'
        },
        {
          title: '毛重',
          align: 'center',
          dataIndex: 'grossWeight'
        },
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '申请者',
          align: 'center',
          dataIndex: 'applicant'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 187,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/order/mesOrderPurchase/listMesPurchaseItemByMainId',
        delete: '/order/mesOrderPurchase/deleteMesPurchaseItem',
        deleteBatch: '/order/mesOrderPurchase/deleteBatchMesPurchaseItem',
        exportXlsUrl: '/order/mesOrderPurchase/exportMesPurchaseItem',
        importUrl: 'order/mesOrderPurchase/importMesPurchaseItem'
      },
      dictOptions: {
        orderType: [],
        payItem: [],
        currency: [],
        tradeCondition: []
      },
      rules: {
        batchNum: { rules: [{ required: true, message: '请输入批次', trigger: 'blur' }] },
        clientCode: { rules: [{ required: true, message: '请输入客户料号', trigger: 'blur' }] },
        batch: { rules: [{ required: true, message: '请输入批次数量', trigger: 'blur' },{ validator:validatorBatch }] },
        printNum: { rules: [{ required: true, message: '请输入打印张数', trigger: 'blur' }] }
      },
      unPrintNum:'',

    }
  },
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importUrl}/${this.mainId}`
    }
  },
  methods: {
    updateNum(id){
      getAction('/order/mesOrderPurchase/uploadUnreceiveNum',{id:id}).then(res=>{
        if (res.success){
          this.$message.success(res.message)
          this.loadData()
        }else{
          this.$message.error(res.message)
        }
      })
    },
    handlePrint(record) {
      this.unPrintNum = record.unreceiveNum
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visiblePrint = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'batchNum', 'clientCode', 'batch', 'printNum'))
        this.form.setFieldsValue({
          batchNum: dateFormat(new Date(), 'YYYYMMDDhhmmss'),
          clientCode: record.clientCode,
          batch: record.query4,
          printNum: '1'
        })
      })
    },
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let formData = Object.assign(this.model, values)
          let remark = this.handform.remark
          this.handform = {
            id: formData.id,
            unPrintNum: formData.unreceiveNum,
            batchNum: formData.batchNum,
            clientCode: formData.clientCode,
            batch: formData.batch,
            printNum: formData.printNum,
            mobileType: '收货打印',
            remark: remark
          }
          this.$http.get('storage/mesStorageWholesale/printAdd', {
            params: this.handform
          }).then(res => {
            if (res.success) {
              this.unPrintNum = (Number(this.unPrintNum) - Number(this.handform.batch)).toString()
              if (Number(this.unPrintNum) <= 0) {
                this.visiblePrint = false
              } else {
                if (Number(this.unPrintNum) < Number(this.handform.batch)) {
                  // this.handform.batch = this.unPrintNum
                  this.form.setFieldsValue({
                    batch: this.unPrintNum,
                  })
                }
              }
              that.$message.success(res.message)
            } else {
              that.$message.error(res.message)
            }
          })
        }

      })

    },
    print() {
      this.$http.get('storage/mesStorageWholesale/printAdd', {
        params: {}
      }).then(res => {

      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less'
</style>
